<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Many-to-many relationships &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../../../index.html" />
    <link rel="up" title="Examples of model relationship API usage" href="index.html" />
    <link rel="next" title="Many-to-one relationships" href="many_to_one.html" />
    <link rel="prev" title="Examples of model relationship API usage" href="index.html" />



 
<script type="text/javascript" src="../../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../../index.html">Home</a>  |
        <a title="Table of contents" href="../../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../../genindex.html">Index</a>  |
        <a title="Module index" href="../../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="index.html" title="Examples of model relationship API usage">previous</a>
     |
    <a href="../../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="many_to_one.html" title="Many-to-one relationships">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-db-examples-many_to_many">
            
  <div class="section" id="s-many-to-many-relationships">
<span id="many-to-many-relationships"></span><h1>Many-to-many relationships<a class="headerlink" href="#many-to-many-relationships" title="Permalink to this headline">¶</a></h1>
<p>To define a many-to-many relationship, use <a class="reference internal" href="../../../ref/models/fields.html#ref-manytomany"><em>ManyToManyField</em></a>.</p>
<p>In this example, an <tt class="docutils literal"><span class="pre">Article</span></tt> can be published in multiple <tt class="docutils literal"><span class="pre">Publication</span></tt>
objects, and a <tt class="docutils literal"><span class="pre">Publication</span></tt> has multiple <tt class="docutils literal"><span class="pre">Article</span></tt> objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Publication</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">title</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>              <span class="c"># __unicode__ on Python 2</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">title</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">(</span><span class="s">&#39;title&#39;</span><span class="p">,)</span>

<span class="k">class</span> <span class="nc">Article</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">headline</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">publications</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Publication</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>              <span class="c"># __unicode__ on Python 2</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">headline</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">ordering</span> <span class="o">=</span> <span class="p">(</span><span class="s">&#39;headline&#39;</span><span class="p">,)</span>
</pre></div>
</div>
<p>What follows are examples of operations that can be performed using the Python
API facilities. Note that if you are using <a class="reference internal" href="../models.html#intermediary-manytomany"><em>an intermediate model</em></a> for a many-to-many relationship, some of the related
manager&#8217;s methods are disabled, so some of these examples won&#8217;t work with such
models.</p>
<p>Create a couple of <tt class="docutils literal"><span class="pre">Publications</span></tt>:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span> <span class="o">=</span> <span class="n">Publication</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&#39;The Python Journal&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span> <span class="o">=</span> <span class="n">Publication</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&#39;Science News&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p3</span> <span class="o">=</span> <span class="n">Publication</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&#39;Science Weekly&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p3</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>Create an <tt class="docutils literal"><span class="pre">Article</span></tt>:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span> <span class="o">=</span> <span class="n">Article</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&#39;Django lets you build Web apps easily&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>You can&#8217;t associate it with a <tt class="docutils literal"><span class="pre">Publication</span></tt> until it&#8217;s been saved:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">p1</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">ValueError</span>: <span class="n">&#39;Article&#39; instance needs to have a primary key value before a many-to-many relationship can be used.</span>
</pre></div>
</div>
<p>Save it!</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>Associate the <tt class="docutils literal"><span class="pre">Article</span></tt> with a <tt class="docutils literal"><span class="pre">Publication</span></tt>:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">p1</span><span class="p">)</span>
</pre></div>
</div>
<p>Create another <tt class="docutils literal"><span class="pre">Article</span></tt>, and set it to appear in both <tt class="docutils literal"><span class="pre">Publications</span></tt>:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span> <span class="o">=</span> <span class="n">Article</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&#39;NASA uses Python&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">p1</span><span class="p">,</span> <span class="n">p2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">p3</span><span class="p">)</span>
</pre></div>
</div>
<p>Adding a second time is OK:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">p3</span><span class="p">)</span>
</pre></div>
</div>
<p>Adding an object of the wrong type raises <a class="reference external" href="http://docs.python.org/3/library/exceptions.html#TypeError" title="(in Python v3.4)"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a>:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">a1</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">&#39;Publication&#39; instance expected</span>
</pre></div>
</div>
<p>Create and add a <tt class="docutils literal"><span class="pre">Publication</span></tt> to an <tt class="docutils literal"><span class="pre">Article</span></tt> in one step using
<a class="reference internal" href="../../../ref/models/relations.html#django.db.models.fields.related.RelatedManager.create" title="django.db.models.fields.related.RelatedManager.create"><tt class="xref py py-meth docutils literal"><span class="pre">create()</span></tt></a>:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">new_publication</span> <span class="o">=</span> <span class="n">a2</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&#39;Highlights for Children&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">Article</span></tt> objects have access to their related <tt class="docutils literal"><span class="pre">Publication</span></tt> objects:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: The Python Journal&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: Highlights for Children&gt;, &lt;Publication: Science News&gt;, &lt;Publication: Science Weekly&gt;, &lt;Publication: The Python Journal&gt;]</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">Publication</span></tt> objects have access to their related <tt class="docutils literal"><span class="pre">Article</span></tt> objects:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: NASA uses Python&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;, &lt;Article: NASA uses Python&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: NASA uses Python&gt;]</span>
</pre></div>
</div>
<p>Many-to-many relationships can be queried using <a class="reference internal" href="../queries.html#lookups-that-span-relationships"><em>lookups across
relationships</em></a>:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">publications__id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;, &lt;Article: NASA uses Python&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">publications__pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;, &lt;Article: NASA uses Python&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">publications</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;, &lt;Article: NASA uses Python&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">publications</span><span class="o">=</span><span class="n">p1</span><span class="p">)</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;, &lt;Article: NASA uses Python&gt;]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">publications__title__startswith</span><span class="o">=</span><span class="s">&quot;Science&quot;</span><span class="p">)</span>
<span class="go">[&lt;Article: NASA uses Python&gt;, &lt;Article: NASA uses Python&gt;]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">publications__title__startswith</span><span class="o">=</span><span class="s">&quot;Science&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">()</span>
<span class="go">[&lt;Article: NASA uses Python&gt;]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../../../ref/models/querysets.html#django.db.models.query.QuerySet.count" title="django.db.models.query.QuerySet.count"><tt class="xref py py-meth docutils literal"><span class="pre">count()</span></tt></a> function respects
<a class="reference internal" href="../../../ref/models/querysets.html#django.db.models.query.QuerySet.distinct" title="django.db.models.query.QuerySet.distinct"><tt class="xref py py-meth docutils literal"><span class="pre">distinct()</span></tt></a> as well:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">publications__title__startswith</span><span class="o">=</span><span class="s">&quot;Science&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
<span class="go">2</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">publications__title__startswith</span><span class="o">=</span><span class="s">&quot;Science&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">()</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
<span class="go">1</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">publications__in</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">])</span><span class="o">.</span><span class="n">distinct</span><span class="p">()</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;, &lt;Article: NASA uses Python&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">publications__in</span><span class="o">=</span><span class="p">[</span><span class="n">p1</span><span class="p">,</span><span class="n">p2</span><span class="p">])</span><span class="o">.</span><span class="n">distinct</span><span class="p">()</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;, &lt;Article: NASA uses Python&gt;]</span>
</pre></div>
</div>
<p>Reverse m2m queries are supported (i.e., starting at the table that doesn&#8217;t have
a <a class="reference internal" href="../../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a>):</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&lt;Publication: The Python Journal&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&lt;Publication: The Python Journal&gt;]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">article__headline__startswith</span><span class="o">=</span><span class="s">&quot;NASA&quot;</span><span class="p">)</span>
<span class="go">[&lt;Publication: Highlights for Children&gt;, &lt;Publication: Science News&gt;, &lt;Publication: Science Weekly&gt;, &lt;Publication: The Python Journal&gt;]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">article__id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&lt;Publication: The Python Journal&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">article__pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&lt;Publication: The Python Journal&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">article</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&lt;Publication: The Python Journal&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">article</span><span class="o">=</span><span class="n">a1</span><span class="p">)</span>
<span class="go">[&lt;Publication: The Python Journal&gt;]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">article__in</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">])</span><span class="o">.</span><span class="n">distinct</span><span class="p">()</span>
<span class="go">[&lt;Publication: Highlights for Children&gt;, &lt;Publication: Science News&gt;, &lt;Publication: Science Weekly&gt;, &lt;Publication: The Python Journal&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">article__in</span><span class="o">=</span><span class="p">[</span><span class="n">a1</span><span class="p">,</span><span class="n">a2</span><span class="p">])</span><span class="o">.</span><span class="n">distinct</span><span class="p">()</span>
<span class="go">[&lt;Publication: Highlights for Children&gt;, &lt;Publication: Science News&gt;, &lt;Publication: Science Weekly&gt;, &lt;Publication: The Python Journal&gt;]</span>
</pre></div>
</div>
<p>Excluding a related item works as you would expect, too (although the SQL
involved is a little complex):</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">publications</span><span class="o">=</span><span class="n">p2</span><span class="p">)</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;]</span>
</pre></div>
</div>
<p>If we delete a <tt class="docutils literal"><span class="pre">Publication</span></tt>, its <tt class="docutils literal"><span class="pre">Articles</span></tt> won&#8217;t be able to access it:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: Highlights for Children&gt;, &lt;Publication: Science News&gt;, &lt;Publication: Science Weekly&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span> <span class="o">=</span> <span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a1</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>If we delete an <tt class="docutils literal"><span class="pre">Article</span></tt>, its <tt class="docutils literal"><span class="pre">Publications</span></tt> won&#8217;t be able to access it:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>Adding via the &#8216;other&#8217; end of an m2m:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span> <span class="o">=</span> <span class="n">Article</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&#39;NASA finds intelligent life on Earth&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">a4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: NASA finds intelligent life on Earth&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: Science News&gt;]</span>
</pre></div>
</div>
<p>Adding via the other end using keywords:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">new_article</span> <span class="o">=</span> <span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&#39;Oxygen-free diet works wonders&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: NASA finds intelligent life on Earth&gt;, &lt;Article: Oxygen-free diet works wonders&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a5</span> <span class="o">=</span> <span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()[</span><span class="mi">1</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a5</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: Science News&gt;]</span>
</pre></div>
</div>
<p>Removing <tt class="docutils literal"><span class="pre">Publication</span></tt> from an <tt class="docutils literal"><span class="pre">Article</span></tt>:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">p2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: Oxygen-free diet works wonders&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>And from the other end:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">a5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a5</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>Relation sets can be assigned. Assignment clears any existing set members:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: Science News&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span><span class="o">.</span><span class="n">publications</span> <span class="o">=</span> <span class="p">[</span><span class="n">p3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: Science Weekly&gt;]</span>
</pre></div>
</div>
<p>Relation sets can be cleared:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>And you can clear from the other end:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">a4</span><span class="p">,</span> <span class="n">a5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: NASA finds intelligent life on Earth&gt;, &lt;Article: Oxygen-free diet works wonders&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: Science News&gt;, &lt;Publication: Science Weekly&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a4</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: Oxygen-free diet works wonders&gt;]</span>
</pre></div>
</div>
<p>Recreate the <tt class="docutils literal"><span class="pre">Article</span></tt> and <tt class="docutils literal"><span class="pre">Publication</span></tt> we have deleted:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span> <span class="o">=</span> <span class="n">Publication</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&#39;The Python Journal&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span> <span class="o">=</span> <span class="n">Article</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&#39;NASA uses Python&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">p1</span><span class="p">,</span> <span class="n">p2</span><span class="p">,</span> <span class="n">p3</span><span class="p">)</span>
</pre></div>
</div>
<p>Bulk delete some <tt class="docutils literal"><span class="pre">Publications</span></tt> - references to deleted publications should
go:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">title__startswith</span><span class="o">=</span><span class="s">&#39;Science&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Publication</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: Highlights for Children&gt;, &lt;Publication: The Python Journal&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;, &lt;Article: NASA finds intelligent life on Earth&gt;, &lt;Article: NASA uses Python&gt;, &lt;Article: Oxygen-free diet works wonders&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: The Python Journal&gt;]</span>
</pre></div>
</div>
<p>Bulk delete some articles - references to deleted objects should go:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__startswith</span><span class="o">=</span><span class="s">&#39;Django&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="n">q</span><span class="p">)</span>
<span class="go">[&lt;Article: Django lets you build Web apps easily&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>
</div>
<p>After the <a class="reference internal" href="../../../ref/models/querysets.html#django.db.models.query.QuerySet.delete" title="django.db.models.query.QuerySet.delete"><tt class="xref py py-meth docutils literal"><span class="pre">delete()</span></tt></a>, the
<a class="reference internal" href="../../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a> cache needs to be cleared, and the
referenced objects should be gone:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="n">q</span><span class="p">)</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Article: NASA uses Python&gt;]</span>
</pre></div>
</div>
<p>An alternate to calling
<a class="reference internal" href="../../../ref/models/relations.html#django.db.models.fields.related.RelatedManager.clear" title="django.db.models.fields.related.RelatedManager.clear"><tt class="xref py py-meth docutils literal"><span class="pre">clear()</span></tt></a> is to assign the
empty set:</p>
<div class="highlight-pycon"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span><span class="o">.</span><span class="n">article_set</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span><span class="o">.</span><span class="n">article_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span> <span class="o">=</span> <span class="p">[</span><span class="n">p1</span><span class="p">,</span> <span class="n">new_publication</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Publication: Highlights for Children&gt;, &lt;Publication: The Python Journal&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a2</span><span class="o">.</span><span class="n">publications</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="index.html">Examples of model relationship API usage</a></li>
    
    
      <li>Next: <a href="many_to_one.html">Many-to-one relationships</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="../../index.html">Using Django</a>
        
          <ul><li><a href="../index.html">Models and databases</a>
        
          <ul><li><a href="index.html">Examples of model relationship API usage</a>
        
        <ul><li>Many-to-many relationships</li></ul>
        </li></ul></li></ul></li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../../_sources/topics/db/examples/many_to_many.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="index.html" title="Examples of model relationship API usage">previous</a>
     |
    <a href="../../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="many_to_one.html" title="Many-to-one relationships">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>